/* ------------------------------------------------------------------------------
 *
 *  # Custom JS code
 *
 *  Place here all your custom js. Make sure it's loaded after app.js
 *
 * ---------------------------------------------------------------------------- */
document.addEventListener('DOMContentLoaded', function() {
    $("select:not(.multiselect):not(.nativeSelect)").select2({
        placeholder: '请选择一条记录'
        ,minimumResultsForSearch: 10   //  超过10条记录显示搜索框
        ,allowClear:true
    }).on("select2:close", function(e) {
        // 监听select2关闭自动触发jquery-validate校验
        $(e.target).valid();
    });
    $('.tokenfield').tokenfield();
    $('.multiselect').multiselect({
        nonSelectedText: '下拉可多选'
        ,numberDisplayed: 3
        ,allSelectedText: '全部选定'
    });
    $(':file').uniform({
        fileButtonClass: "action btn btn-primary"
        ,fileButtonHtml: "选择文件"
        ,filesButtonHtml: "选择文件"
        ,fileClass: "uniform-uploader"
        ,fileDefaultHtml: "未选择文件"
        ,filenameClass: "filename"
    });
});
layer.config({
    skin: 'layui-layer-custom' // 设置默认主题
    ,area: '360px'
})

/**
 * 获取Layui-table复选框的值
 * @param layuiTableId
 * @returns {Object|boolean}
 */
function getLayuiTableIdsObject(layuiTableId){
    let resultObject = {};
    // console.log('layuiTableId',layuiTableId);
    let checkStatus = layui.table.checkStatus(layuiTableId);
    console.trace('checkStatus.data',checkStatus.data);
    let ids =[];
    let noInvalidData = true;
    $.each(checkStatus.data,function(index,obj){
        // console.trace('obj',obj)
        if(obj.id === undefined){
            top.iziToast.error({message: "异常数据，无法执行相关操作！"});
            noInvalidData = false;
            return false;
        }
        if(obj['checkbox_disabled'] !== 'disabled'){
            ids.push(obj.id);
        }
    });
    //  判断正常数据是否存在
    if(noInvalidData && ids.length < 1){
        top.iziToast.warning({message: "未选中数据！"});
        return false;
    }
    resultObject.ids = ids;
    resultObject.status = true;
    resultObject.data = checkStatus.data;
    return resultObject;
}

function importData(){
    layer.open({
        type: 1,
        title:'导入数据',
        offset: 't',
        anim: 'slideDown', // 从下往上
        area: ['100%', '300px'],
        shade: 0.1,
        shadeClose: true,
        content: $('#import-wrapper')
    });
}

function loading(mess){
    if (mess === undefined || mess === ""){
        mess = "正在提交，请稍等...";
    }
    top.$.jBox.tip(mess,'loading',{opacity:0});
}

/**
 * 确认操作
 * @param thisObject    当前触发对象
 * @param msg           提示信息
 * @param resetUrl      重置Url,防止批量操作的时候ids参数值重复叠加
 */
function confirmOperation(thisObject,msg,resetUrl){
    const submit = function(index){
        layer.close(index);
        if($(thisObject).data("url") === undefined){
            top.iziToast.error({message: "功能异常，请联系系统管理员"});
            return false;
        }
        $.ajax({
            url: $(thisObject).data("url")
           ,type: "POST"
           ,success: function(response, status, xhr) {
                top.iziToast.show({message: response.message,icon: 'ico-' + response.status ,color: response.status ==='success'? 'green' :'red'});
                if(response.status === 'success'){
                    location.reload();
                }
                if(resetUrl){
                    $(thisObject).data('url',resetUrl);
                }
            }
            ,error: function(xhr, status, error) {
                top.iziToast.error({message: "请求失败，响应状态：" + xhr.status});
                if(resetUrl){
                    $(thisObject).data('url',resetUrl);
                }
            }
        });
    }
    layer.confirm(msg, {icon: 3}, submit);
}

/**
 * 确认提交
 * @param url  提交地址
 * @param msg  提示信息
 */
function confirmSubmit(url,msg){
    const submit = function(index){
        layer.close(index);
        $.ajax({
            url: url
            ,type: "POST"
            ,success: function(response, status, xhr) {
                top.iziToast.show({message: response.message,icon: 'ico-' + response.status ,color: response.status ==='success'? 'green' :'red'});
                if(response.status === 'success'){
                    location.reload();
                }
            }
            ,error: function(xhr, status, error) {
                top.iziToast.error({message: "请求失败，响应状态：" + xhr.status});
            }
        });
    }
    layer.confirm(msg, {icon: 3}, submit);
}

/**
 * 批量操作选中的数据
 * @param thisObject    当前触发对象
 * @param layuiTableId  layui-table 设置的ID值
 * @param msg
 */
function batchConfirmOperation(thisObject,layuiTableId,msg){
    let idsObject = getLayuiTableIdsObject(layuiTableId);
    if(idsObject['status']){
        const originURL = $(thisObject).data('url');
        $(thisObject).data('url',originURL + idsObject['ids']);
       confirmOperation(thisObject,msg || '是否要操作选中的数据？',originURL);
    }
}

/**
 * 确认修改选中的数据
 * @param thisObject
 * @param layuiTableId
 * @param title
 * @returns {boolean}
 */
function confirmUpdate(thisObject,layuiTableId,title){
    let idsObject = getLayuiTableIdsObject(layuiTableId);
    if(idsObject['status']){
        if(idsObject['ids'].length > 1){
            top.iziToast.warning({message: "只能选中一条数据修改！"});
            return false;
        }
        const url = $(thisObject).data('url') + idsObject['ids'];
        if(!title){
            location.href= url;
        }else{
            popupLayerLeft(title,url);
        }
    }
}

function getLayuiTableHeight(){
    const bodyHeight = $('body').height();
    const contentPadding = parseInt($('.content').css('padding-top') || 0) + parseInt($('.content').css('padding-bottom') || 0);
    const navHeight = $('.nav.nav-tabs').outerHeight(true) || 0;
    const searchHeight = $('#searchForm').outerHeight(true) || 0;
    const btnHeight = $('#optButtonGroup').outerHeight(true) || 0;
    const pageHeight = $('#layPage').outerHeight(true) || 0;
    // console.log('bodyHeight:',bodyHeight, 'contentPadding: ',contentPadding ,'navHeight: ',navHeight ,'searchHeight: ',searchHeight,'btnHeight: ', btnHeight ,'pageHeight: ',pageHeight)
    return bodyHeight - contentPadding - navHeight - searchHeight - btnHeight - pageHeight - 2;
}


function getQueryString(name, url) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    if (!url || url === ""){
        url = window.location.search;
    }else{
        url = url.substring(url.indexOf("?"));
    }
    r = url.substring(1).match(reg)
    if (r != null) return unescape(r[2]); return null;
}

/**
 * 弹出全屏
 * @param thisObject   this对象
 * @param title 弹出框标题
 * @param reload  关闭是否刷新页面
 */
function popupLayerFull(thisObject,title,reload){
    let index = layer.open({
        type: 2
        ,title:  title || false
        ,closeBtn:  title || false
        ,anim:0
        ,area: ['100%', '100%']
        ,content:$(thisObject).data("url")
        ,end:function () {
            if(reload){location.reload();}
        }
    });
    layer.full(index);
}

function popupLayerFull2Parent(thisObject,title,reload){
    let index = parent.layer.open({
        type: 2
        ,title:  title || false
        ,closeBtn:  title || false
        ,anim:0
        ,area: ['100%', '100%']
        ,content:$(thisObject).data("url")
        ,end:function () {
            if(reload){location.reload();}
        }
    });
    layer.full(index);
}
function popupLayerNoTitle(thisObject,isParent){
    let layerObject = layer;
    if(isParent){
        layerObject = parent.layer;
    }
    layerObject.open({
        type: 2
        ,title: false
        ,closeBtn: false
        ,anim: 0
        ,area: ['90%', '90%']
        ,content:$(thisObject).data("url")
    });
}

function selectedCheckbox(layuiTableId){
    let idsObject = getLayuiTableIdsObject(layuiTableId);
    if(idsObject['status']){
        cancelSelect();
        parent.recallSubpageData(idsObject['ids']);
    }
}
function selectedRadio(layuiTableId){
    let idsObject = getLayuiTableIdsObject(layuiTableId);
    if(idsObject['status']){
        cancelSelect();
        parent.recallSubpageData(idsObject['data']);
    }
}
function cancelSelect(){
    //  先得到当前iframe层的索引
    const index = parent.layer.getFrameIndex(window.name);
    //  再执行关闭
    parent.layer.close(index);
}

function popupLayerLeft(title,url){
    layer.open({
        type: 2,
        title: title,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['70%', '100%'],
        shade: 0.1,
        shadeClose: true,
        content: url
    });
}

function ajaxForm(form){
    $.ajax({
        url: $(form).attr('action'),
        type: "POST",
        data: $(form).serialize(),
        success: function(response,status, xhr) {
            top.iziToast.show({message: response.message,icon: 'ico-' + response.status ,color: response.status ==='success'? 'green' :'red'});
            if(response.status === 'success'){
                parent.location.reload();
            }
        },
        error: function(xhr, status, error) {
            top.iziToast.error({message: "请求失败，响应状态：" + xhr.status});
        }
    });
}

function disabledLayuiTableCheckbox(index){
    $(".layui-table tr[data-index="+index+"] input[type='checkbox']").prop('disabled',true);
    $(".layui-table tr[data-index="+index+"] input[type='checkbox']").next().addClass('layui-checkbox-disabled layui-disabled');
    $(".layui-table tr[data-index="+index+"]").addClass('layui-table-checked-disabled');
    $(".layui-table-fixed .layui-table tr[data-index="+index+"]").addClass('layui-table-checked-disabled');
}
function popupLayerTable(thisObject){
    top.layer.open({
        type: 2
        ,title: false
        ,closeBtn: false
        ,anim: 0
        ,area: ['80%', '90%']
        ,content:$(thisObject).data("url")
        ,btn: ['确定', '取消']
        ,yes: function(index, layero){
            let layuiTable = layero.find("iframe")[0].contentWindow.layui.table;
            let checkStatus = layuiTable.checkStatus('layui-table-id1');
            let ids =[];
            //  有效数据
            let validData = true;
            $.each(checkStatus.data,function(index,obj){
                if(obj.id === undefined){
                    top.iziToast.error({title: '异常数据',message: '请检查数据是否正常！'});
                    validData = false;
                    return false;
                }
                ids.push(obj.id);
            });
            //  判断正常数据是否存在
            if(validData && ids.length < 1){
                top.iziToast.warning({title: '警告',message: '请选择数据！'});
                return false;
            }
            // 执行回调函数
            $('#ids').val(ids);
            $('#inputForm').submit();
            top.layer.close(index);
        }
    });
}

function resetForm(){
    $(':input','#searchForm').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
    $('select').val(null).trigger('change');
    $('.input-group-search,.has-feedback').find(':hidden').val('');
}
function validateErrorPlacement(error, element) {

    // Styled checkboxes, radios, bootstrap switch
    if (element.parents('div').hasClass("checker") || element.parents('div').hasClass("choice") || element.parent().hasClass('bootstrap-switch-container') ) {
        if(element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
            error.appendTo( element.parent().parent().parent().parent() );
        }
        else {
            error.appendTo( element.parent().parent().parent().parent().parent() );
        }
    }

    // Unstyled checkboxes, radios
    else if (element.parents('div').hasClass('checkbox') || element.parents('div').hasClass('radio')) {
        error.appendTo( element.parent().parent().parent() );
    }

    // icheck checkboxes, radios
    else if (element.hasClass('icheck')) {
        error.appendTo( element.parent().parent());
    }

    // Input with icons and Select2
    else if (element.parents('div').hasClass('has-feedback') || element.hasClass('select2-hidden-accessible')) {
        error.appendTo( element.parent() );
    }

    // Inline checkboxes, radios
    else if (element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
        error.appendTo( element.parent().parent() );
    }

    // Input group, styled file input
    else if (element.parents('.input-group').children('.input-group-addon').length === 1) {
        element.parents('.input-group').after(error);
    }
    else if (element.parent().hasClass('uploader') || element.parent().hasClass('uniform-uploader')
        || element.parents().hasClass('input-group')
        || element.parents('div').hasClass('tokenfield')) {
        error.appendTo( element.parent().parent() );
    }
    else {
        error.insertAfter(element);
    }
}